package com.cheche.dn.infrastructure.validator;

import com.google.common.collect.Sets;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.Set;

/**
 * Created by cheshun on 15/9/5.
 */
public class IntTypeValidator implements ConstraintValidator<IntType, Integer> {

    private Set<Integer> values;

    @Override
    public void initialize(IntType constraintAnnotation) {
        int[] ints = constraintAnnotation.value();
        values = Sets.newHashSetWithExpectedSize(ints.length);
        for (int i : ints) {
            values.add(i);
        }
    }

    @Override
    public boolean isValid(Integer value, ConstraintValidatorContext context) {
        // null values are valid
        return value == null || values.contains(value);
    }

}
